package com.yuan.homework.listener;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.List;

/**
 * @program: Train
 * @description:
 * @author: yuan_boss
 * @create: 2022-11-21 19:02
 **/

@WebListener
public class MySessionListener implements HttpSessionListener, HttpSessionAttributeListener {
    @Override
    public void sessionCreated(HttpSessionEvent se) {

    }


    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        String loginUser = (String)se.getSession().getAttribute("loginUser");
        //获取上下文对象
        List<String> userList = (List<String>)se.getSession().getServletContext().getAttribute("userList");
        //从上下文对象中移除用户
        userList.remove(loginUser);
        System.out.println("用户信息:" + loginUser + "从application中移除");

    }

    @Override
    public void attributeAdded(HttpSessionBindingEvent se) {
        String loginUser = (String)se.getSession().getAttribute("loginUser");
        if (loginUser != null){
            System.out.println("session创建: " + loginUser);
            //将登录的用户信息放入application
            List<String> userList = (List<String>)se.getSession().getServletContext().getAttribute("userList");
            userList.add(loginUser);
            System.out.println("用户信息:" + loginUser + "已存入application");
        }
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent se) {

    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent se) {
        String loginUser = (String)se.getSession().getAttribute("loginUser");
        List<Integer> flag = (List<Integer>)se.getSession().getServletContext().getAttribute("flag");
        if (loginUser != null ){
            List<String> userList = (List<String>)se.getSession().getServletContext().getAttribute("userList");
            for (String s : userList) {
                if (loginUser.equals(s)){
                    //设置重复登录的标志
                    flag.set(0,1);
                    return;
                }
            }
            attributeAdded(se);
        }

    }
}
